package com.ybkj.daijia.server.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.common.FileUploadVo;
import com.ybkj.daijia.common.MediaUtil;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.server.service.DriverApplyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.MemberApplyService;
import com.ybkj.daijia.server.service.ReceiptService;
import com.ybkj.daijia.server.service.WeixinManagerTixianRecordService;
import com.ybkj.daijia.server.service.ZhuancheService;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;


@Controller
@RequestMapping(value = "common")
public class CommonController {

    /**
     * kindeditor
     */
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private WeixinManagerTixianRecordService weixinManagerTixianRecordService;
    @Autowired
    private MemberApplyService memberApplyService;
    @Autowired
    private ReceiptService receiptService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private DriverApplyService driverApplyService;
    @Autowired
    private ErrandService errandService;
    @Autowired
    private ZhuancheService zhuancheService;

    @RequestMapping(value = "topMessage", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> topMessage() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Map<String, Object> map = new HashMap<String, Object>();

        Long tixianAmount = 0L;
        Long applyMemberAmount = 0L;
        Long receiptAmount = 0L;
        Long lessDriverAmount = 0L;
        Long applyDriverAmount = 0L;
        Long newRentOrderAmount = 0L;
        Long queryByOverhaulTimeLong = 0L;
        Long queryByInsuranceTimeLong = 0L;

        if (subject.isPermitted("managertixian")) {
            if (!principal.isCompanyType()) {
                tixianAmount = weixinManagerTixianRecordService
                    .countNewByCompany(principal.getCompanyId());
            } else {
                tixianAmount = weixinManagerTixianRecordService.countNewByCompany(null);
            }
        }
        if (subject.isPermitted("memberapply")) {
            applyMemberAmount = memberApplyService.countAll();
        }
        if (subject.isPermitted("receipt")) {
            receiptAmount = receiptService.findReceiptNumber();
        }
        if (subject.isPermitted("driver")) {
            lessDriverAmount = driverService.countAllLess();
        }
        if (subject.isPermitted("driverapply")) {
            applyDriverAmount = driverApplyService.countAll();
        }
        ServiceSetting serviceSetting = ServiceUtil.checkOpen();

        if (serviceSetting.isZhuanche()) {
            if (subject.isPermitted("zhuan")) {
                queryByOverhaulTimeLong = zhuancheService.queryByOverhaulTimeLong();
                queryByInsuranceTimeLong = zhuancheService.queryByInsuranceTimeLong();
            }
        }
        map.put("queryByInsuranceTimeLong", queryByInsuranceTimeLong);
        map.put("queryByOverhaulTimeLong", queryByOverhaulTimeLong);
        map.put("tixianAmount", tixianAmount);
        map.put("applyMemberAmount", applyMemberAmount);
        map.put("receiptAmount", receiptAmount);
        map.put("lessDriverAmount", lessDriverAmount);
        map.put("applyDriverAmount", applyDriverAmount);
        map.put("newRentOrderAmount", newRentOrderAmount);

        return map;

    }

    @RequestMapping(method = RequestMethod.POST, value = "uploadimg")
    public void upload(
        @RequestParam("upload_img_token") Long upload_img_token,
        @RequestParam("imgFile") MultipartFile imgFile,
        HttpServletResponse resp,
        HttpServletRequest req) throws IOException {

        FileUploadVo vo = new FileUploadVo();

        Object time_logo_token_obj = req.getSession().getAttribute("upload_img_logo_token");
        if (null == time_logo_token_obj || !((Long) time_logo_token_obj).equals(upload_img_token)) {
            vo.setMsg("不能重复上传");
            vo.setSuccess(false);
            resp.setContentType("text/html;charset=UTF-8");
            Writer writer = resp.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

        String moduleName = imgFile.getOriginalFilename();

        if (MediaUtil.isPicture(imgFile, "")) {
            String bathPath = getBasePath(req);
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
            Date now = new Date();
            String monthstr = monthFormat.format(now);

            String filestr = "upload/img/" + monthstr + "/" + now.getTime() + moduleName
                .substring(moduleName.lastIndexOf("."), moduleName.length());

            File f = new File(bathPath, filestr);

//			FileUtils.forceMkdir(f);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); //上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();

                vo.setUrl(filestr);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                Writer writer = resp.getWriter();

                req.getSession().setAttribute("upload_img_logo_token", null);

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);

            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                resp.setContentType("text/html;charset=UTF-8");
                Writer writer = resp.getWriter();
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);

            }
        } else {
            vo.setMsg("只能上传图片");
            vo.setSuccess(false);
            resp.setContentType("text/html;charset=UTF-8");
            Writer writer = resp.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

    }

    //上传跑腿订单图片
    @RequestMapping(method = RequestMethod.POST, value = "uploaderrandimg")
    public @ResponseBody
    FileUploadVo uploadErrandImg(@RequestParam("imgFile") MultipartFile imgFile,
        HttpServletRequest req) throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String moduleName = imgFile.getOriginalFilename();

        if (MediaUtil.isPicture(imgFile, "")) {
            String bathPath = getBasePath(req);
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
            Date now = new Date();
            String monthstr = monthFormat.format(now);
            String type = moduleName
                .substring(moduleName.lastIndexOf(".") + 1, moduleName.length());
            String filestr = "upload/errand/" + monthstr + "/" + now.getTime() + moduleName
                .substring(moduleName.lastIndexOf("."), moduleName.length());
            String minImg = filestr.substring(0, filestr.lastIndexOf(".")) + "min." + type;
            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); //上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                try {
                    Thumbnails.of(f).size(100, 100).toFile(new File(bathPath, minImg));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                vo.setUrl(filestr);
                vo.setMinurl(minImg);
                vo.setSuccess(true);
                return vo;

            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                return vo;
            }
        } else {
            vo.setMsg("只能上传图片");
            vo.setSuccess(false);
            return vo;
        }

    }

    //上传跑腿订单图片(微信来源)
    public @ResponseBody
    FileUploadVo uploadErrandImg2(File imgFile, HttpServletRequest req) throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String bathPath = getBasePath(req);
        SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
        Date now = new Date();
        String monthstr = monthFormat.format(now);
        String type = imgFile.getName()
            .substring(imgFile.getName().lastIndexOf(".") + 1, imgFile.getName().length());
        String filestr = "upload/errand/" + monthstr + "/" + now.getTime() + imgFile.getName()
            .substring(imgFile.getName().indexOf("."), imgFile.getName().length());
        String minImg = filestr.substring(0, filestr.lastIndexOf(".")) + "min." + type;
        File f = new File(bathPath, filestr);

        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }

        try {
            FileUtils.copyFile(imgFile, f);

            try {
                Thumbnails.of(f).size(100, 100).toFile(new File(bathPath, minImg));
            } catch (Exception e) {
                e.printStackTrace();
            }

            vo.setUrl(filestr);
            vo.setMinurl(minImg);
            vo.setSuccess(true);
            return vo;

        } catch (Exception e) {
            vo.setMsg(e.getMessage());
            vo.setSuccess(false);
            return vo;
        }

    }

    /**
     * 上传临时司机照片
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadDriverTemp", method = RequestMethod.POST)
    public void uploadDriverTemp(
        @RequestParam("pic1") MultipartFile pic1,
        @RequestParam("type") String type,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        FileUploadVo vo = new FileUploadVo();

        String moduleName = pic1.getOriginalFilename();

        if (MediaUtil.isPicture(pic1, "")) {

            long maxSize = 2000000;
            if (pic1.getSize() <= maxSize) {
                String bathPath = getBasePath(req);

                File tempDir = new File(bathPath, "upload/drivertemp");

                FileUtils.forceMkdir(tempDir);

                String uid = UUID.randomUUID().toString().replaceAll("-", "");

                String fileName = String.format("%s.jpg", uid);

                byte[] data = pic1.getBytes();

                File newFile = new File(tempDir, fileName);
                //InputStream in = req.getInputStream();
                FileOutputStream out = new FileOutputStream(newFile);
                IOUtils.write(data, out);

                try {

                    int length = 400;
                    if (StringUtils.isNotBlank(type) && type.equals("bigphoto")) {
                        length = 600;
                    }

                    // 读取源图像
                    BufferedImage bi = ImageIO.read(newFile);
                    int srcWidth = bi.getWidth(); // 源图宽度
                    int srcHeight = bi.getHeight(); // 源图高度

                    if (srcWidth > length || srcHeight > length) {
                        int _width = 0;
                        int _height = 0;
                        if (srcWidth > srcHeight) {
                            _width = length;
                            _height = (srcHeight * length) / srcWidth;
                        } else {
                            _height = length;
                            _width = (srcWidth * length) / srcHeight;
                        }
                        Thumbnails.of(newFile).size(_width, _height).toFile(newFile);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                IOUtils.closeQuietly(out);

                vo.setUrl(fileName);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            } else {
                vo.setSuccess(false);
                vo.setMsg("图片不能超过大小限制2M");
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            }
        } else {
            vo.setSuccess(false);
            vo.setMsg("只能上传图片");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

    }

    /**
     * 上传临时司机照片(拍照)
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadDriverVideoTemp", method = RequestMethod.POST)
    public void uploadDriverVideoTemp(
        @RequestParam("pic1") MultipartFile pic1,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String bathPath = getBasePath(req);

        File tempDir = new File(bathPath, "upload/drivertemp");

        FileUtils.forceMkdir(tempDir);

        String uid = UUID.randomUUID().toString().replaceAll("-", "");

        String fileName = String.format("%s.jpg", uid);

        byte[] data = pic1.getBytes();

        //InputStream in = req.getInputStream();
        FileOutputStream out = new FileOutputStream(new File(tempDir, fileName));
        IOUtils.write(data, out);
        //IOUtils.copy(in, out);
        IOUtils.closeQuietly(out);
        //IOUtils.closeQuietly(in);

        FileUploadVo vo = new FileUploadVo();
        vo.setUrl(fileName);
        vo.setSuccess(true);
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("utf-8");
        Writer writer = resp.getWriter();

        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(writer, vo);
    }

    /**
     * 图片裁剪
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "photoScale", method = RequestMethod.POST)
    public void photoScale(
        @RequestParam("url") String url,
        @RequestParam("type") String type,
        @RequestParam("x") int x,
        @RequestParam("y") int y,
        @RequestParam("width") int width,
        @RequestParam("height") int height,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String bathPath = getBasePath(req);

        File tempDir = new File(bathPath, "upload/" + type);

        FileUtils.forceMkdir(tempDir);

        String fileName = String.format("%s.jpg", UUID.randomUUID().toString().replaceAll("-", ""));

        File oldFile = new File(bathPath, url);
        File newFile = new File(tempDir, fileName);
        try {
            Image img;
            ImageFilter cropFilter;
            // 读取源图像
            BufferedImage bi = ImageIO.read(oldFile);
            int srcWidth = bi.getWidth(); // 源图宽度
            int srcHeight = bi.getHeight(); // 源图高度
            Image image = bi.getScaledInstance(srcWidth, srcHeight,
                Image.SCALE_DEFAULT);

            cropFilter = new CropImageFilter(x, y, width, height);
            img = Toolkit.getDefaultToolkit().createImage(
                new FilteredImageSource(image.getSource(), cropFilter));
            BufferedImage tag = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(img, 0, 0, null);
            g.dispose();

            ImageIO.write(tag, "jpg", newFile);

        } catch (Exception e) {
            e.printStackTrace();
        }

        oldFile.delete();

        resp.setContentType("text/plain;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println(fileName);
    }

    /**
     * 上传驾照(拍照)
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadLicenseVideo", method = RequestMethod.POST)
    public void uploadLicenseVideo(
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String bathPath = getBasePath(req);

        File licenseDir = new File(bathPath, "upload/license");

        FileUtils.forceMkdir(licenseDir);

        String uid = UUID.randomUUID().toString().replaceAll("-", "");

        String fileName = String.format("%s.jpg", uid);

        String base64 = req.getParameter("pic1");
        byte[] data = Base64.decode(base64);

        //InputStream in = req.getInputStream();
        FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
        IOUtils.write(data, out);
        //IOUtils.copy(in, out);
        IOUtils.closeQuietly(out);
        //IOUtils.closeQuietly(in);

        resp.setContentType("text/plain;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println(fileName);

    }

    /**
     * 上传行驶证(拍照)
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadTravelVideo", method = RequestMethod.POST)
    public void uploadTravelVideo(
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String bathPath = getBasePath(req);

        File licenseDir = new File(bathPath, "upload/travel");

        FileUtils.forceMkdir(licenseDir);

        String uid = UUID.randomUUID().toString().replaceAll("-", "");

        String fileName = String.format("%s.jpg", uid);

        String base64 = req.getParameter("pic1");
        byte[] data = Base64.decode(base64);

        //InputStream in = req.getInputStream();
        FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
        IOUtils.write(data, out);
        //IOUtils.copy(in, out);
        IOUtils.closeQuietly(out);
        //IOUtils.closeQuietly(in);

        resp.setContentType("text/plain;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println(fileName);

    }

    /**
     * 上传驾照(本地)
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadLicense", method = RequestMethod.POST)
    public void uploadLicense(
        @RequestParam("pic1") MultipartFile pic1,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String moduleName = pic1.getOriginalFilename();
        if (MediaUtil.isPicture(pic1, "")) {
            if (pic1.getSize() <= 2000000) {//2m
                String bathPath = getBasePath(req);

                File licenseDir = new File(bathPath, "upload/license");

                FileUtils.forceMkdir(licenseDir);

                String uid = UUID.randomUUID().toString().replaceAll("-", "");

                String fileName = String.format("%s.jpg", uid);

                byte[] data = pic1.getBytes();

                //InputStream in = req.getInputStream();
                FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
                IOUtils.write(data, out);
                //IOUtils.copy(in, out);
                IOUtils.closeQuietly(out);
                //IOUtils.closeQuietly(in);

                FileUploadVo vo = new FileUploadVo();
                vo.setUrl(fileName);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            } else {
                FileUploadVo vo = new FileUploadVo();
                vo.setSuccess(false);
                vo.setMsg("图片不能超过大小限制2M");
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            }
        } else {
            FileUploadVo vo = new FileUploadVo();
            vo.setSuccess(false);
            vo.setMsg("只能上传图片");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

    }

    /**
     * 上传行驶证(本地)
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadTravel", method = RequestMethod.POST)
    public void uploadTravel(
        @RequestParam("pic1") MultipartFile pic1,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String moduleName = pic1.getOriginalFilename();
        if (MediaUtil.isPicture(pic1, "")) {
            if (pic1.getSize() <= 2000000) {//2m
                String bathPath = getBasePath(req);

                File licenseDir = new File(bathPath, "upload/travel");

                FileUtils.forceMkdir(licenseDir);

                String uid = UUID.randomUUID().toString().replaceAll("-", "");

                String fileName = String.format("%s.jpg", uid);

                byte[] data = pic1.getBytes();

                //InputStream in = req.getInputStream();
                FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
                IOUtils.write(data, out);
                //IOUtils.copy(in, out);
                IOUtils.closeQuietly(out);
                //IOUtils.closeQuietly(in);

                FileUploadVo vo = new FileUploadVo();
                vo.setUrl(fileName);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            } else {
                FileUploadVo vo = new FileUploadVo();
                vo.setSuccess(false);
                vo.setMsg("图片不能超过大小限制2M");
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            }
        } else {
            FileUploadVo vo = new FileUploadVo();
            vo.setSuccess(false);
            vo.setMsg("只能上传图片");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

    }

    @RequestMapping(value = "uploadQualificationPhoto", method = RequestMethod.POST)
    public void updateQualificationPhoto(@RequestParam("pic1") MultipartFile pic1,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String moduleName = pic1.getOriginalFilename();
        if (MediaUtil.isPicture(pic1, "")) {
            if (pic1.getSize() <= 2000000) {//2m
                String bathPath = getBasePath(req);

                File licenseDir = new File(bathPath, "upload/qualificationPhoto");

                FileUtils.forceMkdir(licenseDir);

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

                String fileName = String
                    .format("%s.png", df.format(new Date()) + "_" + new Random().nextInt(1000));

                byte[] data = pic1.getBytes();

                //InputStream in = req.getInputStream();
                FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
                IOUtils.write(data, out);
                //IOUtils.copy(in, out);
                IOUtils.closeQuietly(out);
                //IOUtils.closeQuietly(in);

                FileUploadVo vo = new FileUploadVo();
                vo.setUrl(fileName);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            } else {
                FileUploadVo vo = new FileUploadVo();
                vo.setSuccess(false);
                vo.setMsg("图片不能超过大小限制2M");
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            }
        } else {
            FileUploadVo vo = new FileUploadVo();
            vo.setSuccess(false);
            vo.setMsg("只能上传图片");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }
    }

    /**
     * 上传司机照片(拍照)
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadDriverPhotoVideo", method = RequestMethod.POST)
    public void uploadDriverPhotoVideo(
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String bathPath = getBasePath(req);

        File licenseDir = new File(bathPath, "upload/driver");

        FileUtils.forceMkdir(licenseDir);

        String uid = req.getParameter("uid");

        String fileName = String.format("%s.jpg", uid);

        String base64 = req.getParameter("pic1");
        byte[] data = Base64.decode(base64);

        //InputStream in = req.getInputStream();
        FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
        IOUtils.write(data, out);
        //IOUtils.copy(in, out);
        IOUtils.closeQuietly(out);
        //IOUtils.closeQuietly(in);

        resp.setContentType("text/plain;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println(fileName);

    }

    /**
     * 上传司机照片(本地)
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadDriverPhoto", method = RequestMethod.POST)
    public void uploadDriverPhoto(
        @RequestParam("pic1") MultipartFile pic1,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        if (pic1.getSize() <= 153600) {//150kb
            String bathPath = getBasePath(req);

            File licenseDir = new File(bathPath, "upload/driver");

            FileUtils.forceMkdir(licenseDir);

            String uid = UUID.randomUUID().toString().replaceAll("-", "");

            String fileName = String.format("%s.jpg", uid);

            byte[] data = pic1.getBytes();

            //InputStream in = req.getInputStream();
            FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
            IOUtils.write(data, out);
            //IOUtils.copy(in, out);
            IOUtils.closeQuietly(out);
            //IOUtils.closeQuietly(in);

            FileUploadVo vo = new FileUploadVo();
            vo.setUrl(fileName);
            vo.setSuccess(true);
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        } else {
            FileUploadVo vo = new FileUploadVo();
            vo.setSuccess(false);
            vo.setMsg("图片大小不能超过150KB");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }


    }

    /**
     * 上传司机大图(本地)
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadDriverBigPhoto", method = RequestMethod.POST)
    public void uploadDriverBigPhoto(
        @RequestParam("pic1") MultipartFile pic1,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        if (pic1.getSize() <= 307200) {//300kb
            String bathPath = getBasePath(req);

            File licenseDir = new File(bathPath, "upload/driverbigphoto");

            FileUtils.forceMkdir(licenseDir);

            String uid = req.getParameter("uid");

            String fileName = String.format("%s.jpg", uid);

            byte[] data = pic1.getBytes();

            //InputStream in = req.getInputStream();
            FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
            IOUtils.write(data, out);
            //IOUtils.copy(in, out);
            IOUtils.closeQuietly(out);
            //IOUtils.closeQuietly(in);

            FileUploadVo vo = new FileUploadVo();
            vo.setUrl(fileName);
            vo.setSuccess(true);
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        } else {
            FileUploadVo vo = new FileUploadVo();
            vo.setSuccess(false);
            vo.setMsg("图片大小不能超过300KB");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

    }

    /**
     * 上传司机身份证(本地)
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadIdCardPhoto", method = RequestMethod.POST)
    public void uploadIdCardPhoto(@RequestParam("pic1") MultipartFile pic1, HttpServletRequest req,
        HttpServletResponse resp) throws IOException {
        String moduleName = pic1.getOriginalFilename();
        if (MediaUtil.isPicture(pic1, "")) {
            if (pic1.getSize() <= 2000000) {//2m
                String bathPath = getBasePath(req);

                File licenseDir = new File(bathPath, "upload/idCardPhoto");

                FileUtils.forceMkdir(licenseDir);

                String uid = UUID.randomUUID().toString().replaceAll("-", "");

                String fileName = String.format("%s.jpg", uid);

                byte[] data = pic1.getBytes();

                //InputStream in = req.getInputStream();
                FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
                IOUtils.write(data, out);
                //IOUtils.copy(in, out);
                IOUtils.closeQuietly(out);
                //IOUtils.closeQuietly(in);

                FileUploadVo vo = new FileUploadVo();
                vo.setUrl(fileName);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            } else {
                FileUploadVo vo = new FileUploadVo();
                vo.setSuccess(false);
                vo.setMsg("图片不能超过大小限制2M");
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            }
        } else {
            FileUploadVo vo = new FileUploadVo();
            vo.setSuccess(false);
            vo.setMsg("只能上传图片");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

    }

    /**
     * 上传司机身份证反面
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadBackOfIdCardPhoto", method = RequestMethod.POST)
    public void uploadBackOfIdCardPhoto(@RequestParam("pic1") MultipartFile pic1,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String moduleName = pic1.getOriginalFilename();
        if (MediaUtil.isPicture(pic1, "")) {
            if (pic1.getSize() <= 2000000) {//2m
                String bathPath = getBasePath(req);

                File licenseDir = new File(bathPath, "upload/backOfIdCardPhoto");

                FileUtils.forceMkdir(licenseDir);

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

                String fileName = String
                    .format("%s.png", df.format(new Date()) + "_" + new Random().nextInt(1000));

                byte[] data = pic1.getBytes();

                //InputStream in = req.getInputStream();
                FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
                IOUtils.write(data, out);
                //IOUtils.copy(in, out);
                IOUtils.closeQuietly(out);
                //IOUtils.closeQuietly(in);

                FileUploadVo vo = new FileUploadVo();
                vo.setUrl(fileName);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            } else {
                FileUploadVo vo = new FileUploadVo();
                vo.setSuccess(false);
                vo.setMsg("图片不能超过大小限制2M");
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            }
        } else {
            FileUploadVo vo = new FileUploadVo();
            vo.setSuccess(false);
            vo.setMsg("只能上传图片");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

    }

    /**
     * 上传司机手持身份证(本地)
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadIdCardHandPhoto", method = RequestMethod.POST)
    public void uploadIdCardHandPhoto(
        @RequestParam("pic1") MultipartFile pic1,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String moduleName = pic1.getOriginalFilename();
        if (MediaUtil.isPicture(pic1, "")) {
            if (pic1.getSize() <= 2000000) {//2m
                String bathPath = getBasePath(req);

                File licenseDir = new File(bathPath, "upload/idCardHandPhoto");

                FileUtils.forceMkdir(licenseDir);

                String uid = UUID.randomUUID().toString().replaceAll("-", "");

                String fileName = String.format("%s.jpg", uid);

                byte[] data = pic1.getBytes();

                //InputStream in = req.getInputStream();
                FileOutputStream out = new FileOutputStream(new File(licenseDir, fileName));
                IOUtils.write(data, out);
                //IOUtils.copy(in, out);
                IOUtils.closeQuietly(out);
                //IOUtils.closeQuietly(in);

                FileUploadVo vo = new FileUploadVo();
                vo.setUrl(fileName);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            } else {
                FileUploadVo vo = new FileUploadVo();
                vo.setSuccess(false);
                vo.setMsg("图片不能超过大小限制2M");
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            }
        } else {
            FileUploadVo vo = new FileUploadVo();
            vo.setSuccess(false);
            vo.setMsg("只能上传图片");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

    }

    /**
     * 上传临时图片
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadTemp", method = RequestMethod.POST)
    public void uploadTemp(
        @RequestParam("pic1") MultipartFile pic1,
        @RequestParam("type") String type,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String moduleName = pic1.getOriginalFilename();

        if (MediaUtil.isPicture(pic1, "")) {
            String bathPath = getBasePath(req);

            File tempDir = new File(bathPath, "upload/" + type + "");

            FileUtils.forceMkdir(tempDir);

            String uid = UUID.randomUUID().toString().replaceAll("-", "");

            String fileName = String.format("%s.jpg", uid);

            byte[] data = pic1.getBytes();

            File newFile = new File(tempDir, fileName);
            //InputStream in = req.getInputStream();
            FileOutputStream out = new FileOutputStream(newFile);
            IOUtils.write(data, out);

            try {

                int length = 800;
                if (type.equals("driverCarTemp")) {
                    length = 400;
                }

                // 读取源图像
                BufferedImage bi = ImageIO.read(newFile);
                int srcWidth = bi.getWidth(); // 源图宽度
                int srcHeight = bi.getHeight(); // 源图高度

                if (srcWidth > length || srcHeight > length) {
                    int _width = 0;
                    int _height = 0;
                    if (srcWidth > srcHeight) {
                        _width = length;
                        _height = (srcHeight * length) / srcWidth;
                    } else {
                        _height = length;
                        _width = (srcWidth * length) / srcHeight;
                    }

                    Thumbnails.of(newFile).size(_width, _height).toFile(newFile);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            IOUtils.closeQuietly(out);

            vo.setUrl(fileName);
            vo.setSuccess(true);
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        } else {
            vo.setSuccess(false);
            vo.setMsg("只能上传图片");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

    }

//	@RequestMapping(value="uploadTellRecord")
//	public void uploadTellRecord(MultipartHttpServletRequest req,HttpServletResponse resp) throws IOException{
//
//		String bathPath = getBasePath(req);
//
//		MultipartFile file = req.getMultiFileMap().getFirst("filedata1");
//
//		Calendar calendar = Calendar.getInstance();
//		String dir = DateFormatUtils.format(calendar, "yyyy-MM");
//		String subDir = DateFormatUtils.format(calendar, "dd");
//
//		File tellDir =  new File(bathPath,String.format("upload/tell/%s/%s", dir,subDir));
//		FileUtils.forceMkdir(tellDir);
//
//		InputStream in = file.getInputStream();
//		OutputStream out = new FileOutputStream(new File(tellDir, file.getOriginalFilename()));
//
//		IOUtils.copy(in, out);
//		IOUtils.closeQuietly(out);
//		IOUtils.closeQuietly(in);
//
//		resp.setContentType("text/plain;charset=utf-8");
//		resp.setCharacterEncoding("utf-8");
//		PrintWriter writer = resp.getWriter();
//		writer.println("result:1");
//		
//		String srcFileName=tellDir+file.getOriginalFilename();
//		String tarFileName=tellDir+file.getName()+".mp3";
//		
//		
//		Runtime run=null;
//	 	 try{
//			run=Runtime.getRuntime();
//			long start=System.currentTimeMillis();
//			Process p=run.exec("lame -b 16 "+srcFileName+" "+tarFileName); //16为码率，可自行修改
//			//important
//			p.getOutputStream().close();
//			p.getInputStream().close();
//			p.getErrorStream().close();
//			p.waitFor();
//			long end=System.currentTimeMillis();
//		}
//		catch(Exception err){
//			err.printStackTrace();
//		}
//		finally{
//			if(run!=null){
//				run.freeMemory();
//			}
//		}

//	}

    /**
     * 删除图片
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "deleteDriverPhoto", method = RequestMethod.POST)
    public void deleteDriverPhoto(
        @RequestParam("url") String url,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String bathPath = getBasePath(req);
        File photo = new File(bathPath, url);
        if (photo.exists()) {
            photo.delete();
        }

        FileUploadVo vo = new FileUploadVo();
        vo.setSuccess(true);
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("utf-8");
        Writer writer = resp.getWriter();

        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(writer, vo);

    }

    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }

    @RequestMapping(value = "kindeditor/fileupload", method = RequestMethod.POST)
    public void fileUpload(HttpServletRequest request,
        HttpServletResponse resp, @RequestParam("imgFile") MultipartFile imgFile)
        throws ServletException, IOException,
        FileUploadException {

        ServletContext application = request.getSession().getServletContext();
        String savePath = application.getRealPath("/") + "/upload/kindeditor/";

        // 文件保存目录URL
        String saveUrl = request.getContextPath() + "/upload/kindeditor/";

        // 定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        // 最大文件大小
        long maxSize = 2000000;

        resp.setContentType("text/html;charset=UTF-8");
        Writer writer = resp.getWriter();

        ObjectMapper mapper = new ObjectMapper();

        Map<String, Object> msg = new HashMap<String, Object>();

        if (!ServletFileUpload.isMultipartContent(request)) {
            msg.put("error", 1);
            msg.put("message", "请选择文件。");
            mapper.writeValue(writer, msg);
            return;
        }
        // 检查目录
        File uploadDir = new File(savePath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
            //return getError("上传目录不存在。");
        }
        // 检查目录写权限
        if (!uploadDir.canWrite()) {
            msg.put("error", 1);
            msg.put("message", "上传目录没有写权限。");
            mapper.writeValue(writer, msg);
            return;
        }

        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }
        if (!extMap.containsKey(dirName)) {
            msg.put("error", 1);
            msg.put("message", "目录名不正确。");
            mapper.writeValue(writer, msg);
            return;
        }
        // 创建文件夹
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        String fileName = imgFile.getOriginalFilename();
        // 检查文件大小
        if (imgFile.getSize() > maxSize) {
            msg.put("error", 1);
            msg.put("message", "上传文件大小超过限制。");
            mapper.writeValue(writer, msg);
            return;
        }
        // 检查扩展名
        String fileExt = fileName.substring(
            fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String>asList(extMap.get(dirName).split(","))
            .contains(fileExt)) {
            msg.put("error", 1);
            msg.put("message", "上传文件扩展名是不允许的扩展名。\n只允许"
                + extMap.get(dirName) + "格式。");
            mapper.writeValue(writer, msg);
            return;
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_"
            + new Random().nextInt(1000) + "." + fileExt;
        try {
            File uploadedFile = new File(savePath, newFileName);

            File tempDest = new File(System.getProperty("java.io.tmpdir"),
                "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
            imgFile.transferTo(tempDest); //上传到临时文件中
            FileUtils.copyFile(tempDest, uploadedFile);
            tempDest.delete();
        } catch (Exception e) {
            msg.put("error", 1);
            msg.put("message", "上传文件失败。");
            mapper.writeValue(writer, msg);
            return;
        }

        msg.put("error", 0);
        msg.put("url", saveUrl + newFileName);
        mapper.writeValue(writer, msg);
    }


    @RequestMapping(value = "kindeditor/filemanager", method = RequestMethod.GET)
    public void fileManager(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        ServletContext application = request.getSession().getServletContext();
        ServletOutputStream out = response.getOutputStream();
        // 根目录路径，可以指定绝对路径，比如 /var/www/attached/
        String rootPath = application.getRealPath("/") + "/upload/kindeditor/";
        // 根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
        String rootUrl = request.getContextPath() + "/upload/kindeditor/";
        // 图片扩展名
        String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};

        String dirName = request.getParameter("dir");
        if (dirName != null) {
            if (!Arrays.<String>asList(
                new String[]{"image", "flash", "media", "file"})
                .contains(dirName)) {
                out.println("Invalid Directory name.");
                return;
            }
            rootPath += dirName + "/";
            rootUrl += dirName + "/";
            File saveDirFile = new File(rootPath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
        }
        // 根据path参数，设置各路径和URL
        String path = request.getParameter("path") != null ? request
            .getParameter("path") : "";
        String currentPath = rootPath + path;
        String currentUrl = rootUrl + path;
        String currentDirPath = path;
        String moveupDirPath = "";
        if (!"".equals(path)) {
            String str = currentDirPath.substring(0,
                currentDirPath.length() - 1);
            moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0,
                str.lastIndexOf("/") + 1) : "";
        }

        // 排序形式，name or size or type
        String order = request.getParameter("order") != null ? request
            .getParameter("order").toLowerCase() : "name";

        // 不允许使用..移动到上一级目录
        if (path.indexOf("..") >= 0) {
            out.println("Access is not allowed.");
            return;
        }
        // 最后一个字符不是/
        if (!"".equals(path) && !path.endsWith("/")) {
            out.println("Parameter is not valid.");
            return;
        }
        // 目录不存在或不是目录
        File currentPathFile = new File(currentPath);
        if (!currentPathFile.isDirectory()) {
            out.println("Directory does not exist.");
            return;
        }
        // 遍历目录取的文件信息
        List<Hashtable> fileList = new ArrayList<Hashtable>();
        if (currentPathFile.listFiles() != null) {
            for (File file : currentPathFile.listFiles()) {
                Hashtable<String, Object> hash = new Hashtable<String, Object>();
                String fileName = file.getName();
                if (file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else if (file.isFile()) {
                    String fileExt = fileName.substring(
                        fileName.lastIndexOf(".") + 1).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", Arrays.<String>asList(fileTypes)
                        .contains(fileExt));
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime",
                    com.ybkj.daijia.constant.DateConstant.DATE_TIME.format(file
                        .lastModified()));
                fileList.add(hash);
            }
        }

        if ("size".equals(order)) {
            Collections.sort(fileList, new SizeComparator());
        } else if ("type".equals(order)) {
            Collections.sort(fileList, new TypeComparator());
        } else {
            Collections.sort(fileList, new NameComparator());
        }
        Map<String, Object> msg = new HashMap<String, Object>();
        msg.put("moveup_dir_path", moveupDirPath);
        msg.put("current_dir_path", currentDirPath);
        msg.put("current_url", currentUrl);
        msg.put("total_count", fileList.size());
        msg.put("file_list", fileList);
        response.setContentType("application/json; charset=UTF-8");
        String msgStr = objectMapper.writeValueAsString(msg);
        out.println(msgStr);
    }

    //上传活动图片
    @RequestMapping(method = RequestMethod.POST, value = "uploadActivityImg")
    public @ResponseBody
    FileUploadVo uploadActivityImg(@RequestParam("imgFile") MultipartFile imgFile,
        HttpServletRequest req) throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String moduleName = imgFile.getOriginalFilename();

        if (MediaUtil.isPicture(imgFile, "")) {
            String bathPath = getBasePath(req);
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
            Date now = new Date();
            String monthstr = monthFormat.format(now);
            String type = moduleName
                .substring(moduleName.lastIndexOf(".") + 1, moduleName.length());
            String filestr = "upload/activity/" + monthstr + "/" + now.getTime() + moduleName
                .substring(moduleName.lastIndexOf("."), moduleName.length());
            String minImg = filestr.substring(0, filestr.lastIndexOf(".")) + "min." + type;
            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); //上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                try {
                    Thumbnails.of(f).size(100, 100).toFile(new File(bathPath, minImg));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                vo.setUrl(filestr);
                vo.setMinurl(minImg);
                vo.setSuccess(true);
                return vo;

            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                return vo;
            }
        } else {
            vo.setMsg("只能上传图片");
            vo.setSuccess(false);
            return vo;
        }

    }

    @RequestMapping(method = RequestMethod.POST, value = "uploadIdcardimg")
    public @ResponseBody
    FileUploadVo uploadIdcardimg(@RequestParam("imgFile") MultipartFile imgFile,
        HttpServletRequest req) throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String moduleName = imgFile.getOriginalFilename();

        if (MediaUtil.isPicture(imgFile, "")) {
            String bathPath = getBasePath(req);
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
            Date now = new Date();
            String monthstr = monthFormat.format(now);
            String type = moduleName
                .substring(moduleName.lastIndexOf(".") + 1, moduleName.length());
            String filestr = "upload/company/idcard/" + monthstr + "/" + now.getTime() + moduleName
                .substring(moduleName.lastIndexOf("."), moduleName.length());
            String minImg = filestr.substring(0, filestr.lastIndexOf(".")) + "min." + type;
            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); //上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                try {
                    Thumbnails.of(f).size(100, 100).toFile(new File(bathPath, minImg));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                vo.setUrl(filestr);
                vo.setMinurl(minImg);
                vo.setSuccess(true);
                return vo;

            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                return vo;
            }
        } else {
            vo.setMsg("只能上传图片");
            vo.setSuccess(false);
            return vo;
        }

    }

    @RequestMapping(method = RequestMethod.POST, value = "uploadCarImage")
    public @ResponseBody
    FileUploadVo uploadCarImage(
        @RequestParam("upload_img_token") Long upload_img_token,
        @RequestParam("picture") MultipartFile imgFile,
        HttpServletRequest req) throws IOException {

        FileUploadVo vo = new FileUploadVo();

        Object time_body_token_obj = req.getSession().getAttribute("upload_img_body_token");

        if (null == time_body_token_obj || !((Long) time_body_token_obj).equals(upload_img_token)) {
            vo.setMsg("不能重复上传");
            vo.setSuccess(false);
            return vo;
        }

        String moduleName = imgFile.getOriginalFilename();

        if (MediaUtil.isPicture(imgFile, "")) {
            String bathPath = getBasePath(req);
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
            Date now = new Date();
            String monthstr = monthFormat.format(now);
            String type = moduleName
                .substring(moduleName.lastIndexOf(".") + 1, moduleName.length());
            String filestr = "upload/zhuanche/car/" + monthstr + "/" + now.getTime() + moduleName
                .substring(moduleName.lastIndexOf("."), moduleName.length());
            String minImg = filestr.substring(0, filestr.lastIndexOf(".")) + "min." + type;
            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); //上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                try {
                    Thumbnails.of(f).size(100, 100).toFile(new File(bathPath, minImg));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                req.getSession().setAttribute("upload_img_body_token", null);

                vo.setUrl(filestr);
                vo.setMinurl(minImg);
                vo.setSuccess(true);
                return vo;

            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                return vo;
            }
        } else {
            vo.setMsg("只能上传图片");
            vo.setSuccess(false);
            return vo;
        }

    }

    @RequestMapping(method = RequestMethod.POST, value = "uploadPlateImage")
    public @ResponseBody
    FileUploadVo uploadPlateImage(
        @RequestParam("upload_img_token") Long upload_img_token,
        @RequestParam("platePicture") MultipartFile imgFile,
        HttpServletRequest req) throws IOException {

        FileUploadVo vo = new FileUploadVo();
        Object time_plate_token_obj = req.getSession().getAttribute("upload_img_plate_token");
        if (null == time_plate_token_obj || !((Long) time_plate_token_obj)
            .equals(upload_img_token)) {
            vo.setMsg("不能重复上传");
            vo.setSuccess(false);
            return vo;
        }

        String moduleName = imgFile.getOriginalFilename();

        if (MediaUtil.isPicture(imgFile, "")) {
            String bathPath = getBasePath(req);
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
            Date now = new Date();
            String monthstr = monthFormat.format(now);
            String type = moduleName
                .substring(moduleName.lastIndexOf(".") + 1, moduleName.length());
            String filestr = "upload/zhuanche/plate/" + monthstr + "/" + now.getTime() + moduleName
                .substring(moduleName.lastIndexOf("."), moduleName.length());
            String minImg = filestr.substring(0, filestr.lastIndexOf(".")) + "min." + type;
            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); //上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                try {
                    Thumbnails.of(f).size(100, 100).toFile(new File(bathPath, minImg));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                req.getSession().setAttribute("upload_img_plate_token", null);

                vo.setUrl(filestr);
                vo.setMinurl(minImg);
                vo.setSuccess(true);
                return vo;

            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                return vo;
            }
        } else {
            vo.setMsg("只能上传图片");
            vo.setSuccess(false);
            return vo;
        }

    }

    @RequestMapping(method = RequestMethod.POST, value = "uploadZhucheCarImage")
    public @ResponseBody
    FileUploadVo uploadZhucheCarImage(@RequestParam("zhuchepicture") MultipartFile imgFile,
        HttpServletRequest req) throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String moduleName = imgFile.getOriginalFilename();

        if (MediaUtil.isPicture(imgFile, "")) {
            String bathPath = getBasePath(req);
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMMdd");
            Date now = new Date();
            String monthstr = monthFormat.format(now);
            String type = moduleName
                .substring(moduleName.lastIndexOf(".") + 1, moduleName.length());
            String filestr = "upload/zhuche/car/" + monthstr + "/" + now.getTime() + moduleName
                .substring(moduleName.lastIndexOf("."), moduleName.length());
            String minImg = filestr.substring(0, filestr.lastIndexOf(".")) + "min." + type;
            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); //上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                try {
                    Thumbnails.of(f).size(300, 200).toFile(new File(bathPath, minImg));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String basePath =
                    req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req
                        .getContextPath();//+request.getRequestURI();
                vo.setUrl(basePath + "/" + filestr);
                vo.setMinurl(basePath + "/" + minImg);
                vo.setSuccess(true);
                return vo;

            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                return vo;
            }
        } else {
            vo.setMsg("只能上传图片");
            vo.setSuccess(false);
            return vo;
        }

    }

    /**
     * 上传银联支付证书.
     */
    @RequestMapping(method = RequestMethod.POST, value = "uploadFile")
    public void uploadFile(Model model, @RequestParam("uploadFile") MultipartFile imgFile,
        HttpServletResponse resp, HttpServletRequest req) throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String moduleName = imgFile.getOriginalFilename();

        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("file", "cer");
        String fileName = moduleName;
        String dirName = "file";
        // 检查扩展名
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
            vo.setMsg("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
            vo.setSuccess(false);
            resp.setContentType("text/html;charset=UTF-8");
            Writer writer = resp.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        } else {
            String bathPath = getBasePath(req);

            String filestr = "upload/unionpay/" + moduleName;

            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); //上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                vo.setUrl(filestr);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                Writer writer = resp.getWriter();
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                resp.setContentType("text/html;charset=UTF-8");
                Writer writer = resp.getWriter();
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            }
        }

    }

    /**
     * 上传微信商户证书
     */
    @RequestMapping(method = RequestMethod.POST, value = "uploadWxCert")
    public void uploadWxCert(Model model, @RequestParam("certFile") MultipartFile certFile,
        HttpServletResponse resp, HttpServletRequest req) throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String moduleName = certFile.getOriginalFilename();

        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("file", "p12");
        String fileName = moduleName;
        String dirName = "file";
        // 检查扩展名
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
            vo.setMsg("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
            vo.setSuccess(false);
            resp.setContentType("text/html;charset=UTF-8");
            Writer writer = resp.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        } else {
            String bathPath = getBasePath(req);

            //apiclient_cert.p12
            String filestr = "upload/wx/cert/" + moduleName;

            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                certFile.transferTo(tempDest); //上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                vo.setUrl(moduleName);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                Writer writer = resp.getWriter();
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                resp.setContentType("text/html;charset=UTF-8");
                Writer writer = resp.getWriter();
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            }
        }

    }

    class NameComparator implements Comparator {

        public int compare(Object a, Object b) {
            Hashtable hashA = (Hashtable) a;
            Hashtable hashB = (Hashtable) b;
            if (((Boolean) hashA.get("is_dir"))
                && !((Boolean) hashB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) hashA.get("is_dir"))
                && ((Boolean) hashB.get("is_dir"))) {
                return 1;
            } else {
                return ((String) hashA.get("filename"))
                    .compareTo((String) hashB.get("filename"));
            }
        }
    }

    class SizeComparator implements Comparator {

        public int compare(Object a, Object b) {
            Hashtable hashA = (Hashtable) a;
            Hashtable hashB = (Hashtable) b;
            if (((Boolean) hashA.get("is_dir"))
                && !((Boolean) hashB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) hashA.get("is_dir"))
                && ((Boolean) hashB.get("is_dir"))) {
                return 1;
            } else {
                if (((Long) hashA.get("filesize")) > ((Long) hashB
                    .get("filesize"))) {
                    return 1;
                } else if (((Long) hashA.get("filesize")) < ((Long) hashB
                    .get("filesize"))) {
                    return -1;
                } else {
                    return 0;
                }
            }
        }
    }

    class TypeComparator implements Comparator {

        public int compare(Object a, Object b) {
            Hashtable hashA = (Hashtable) a;
            Hashtable hashB = (Hashtable) b;
            if (((Boolean) hashA.get("is_dir"))
                && !((Boolean) hashB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) hashA.get("is_dir"))
                && ((Boolean) hashB.get("is_dir"))) {
                return 1;
            } else {
                return ((String) hashA.get("filetype"))
                    .compareTo((String) hashB.get("filetype"));
            }
        }
    }

}



